package com.appheader.rongmaphone.utils.network;

import android.text.TextUtils;
import android.util.Log;

import com.appheader.rongmaphone.cache.file.ResourceFileManager;
import com.appheader.rongmaphone.utils.FileUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Iterator;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * 下载文件Util，新建该对象要传入更新进步的对象，和控制对象
 * @author alaowan
 *
 */
public class DownloadUtil {
	
	private int fileSize;
	
	private DownloadListener listener;
	
	private CancelLock cancelLock;

	public DownloadUtil(DownloadListener downloadListener) {
	}

	public DownloadUtil(DownloadListener listener, CancelLock cancelLock){
		this.listener = listener;
		this.cancelLock = cancelLock;
	}
	//文件下载
	public String downloadFile(String url, String savePath, String specFileName, Map<String, String> headers) throws IOException, DownloadException {
		int downLoadFileSize = 0;
		URL myURL = new URL(url);
		HttpURLConnection conn = (HttpURLConnection) myURL.openConnection();
		int contentLength = conn.getContentLength();

		File rootDir = new File(savePath);
		//创建目录
		if (!rootDir.exists()) {
			boolean is = rootDir.mkdirs();
			Log.e("IS", "onResponse: ---" + is);
		}

//                                        //下载后的文件名
		String filePath = savePath + "previewZip.zip";
		File file = new File(filePath);
		if (!file.exists()) {
			file.createNewFile();
		}
		if(headers != null && !headers.isEmpty()){
			conn.setAllowUserInteraction(true);
			Iterator<String> iterator = headers.keySet().iterator();
			while (iterator.hasNext()) {
				String key = iterator.next();
				conn.addRequestProperty(key, headers.get(key));
				Log.e("header",key+"||"+headers.get(key));
			}
		}
		conn.setRequestMethod("POST");
		conn.setDoInput(true);
		conn.setDoOutput(true);
		conn.connect();
//		DataOutputStream dos=new DataOutputStream(conn.getOutputStream());
//		dos.writeBytes(param);
//		dos.flush();
//		dos.close();
		InputStream is = conn.getInputStream();
		this.fileSize = conn.getContentLength();// 根据响应获取文件大小
		if (is == null)
			throw new IOException("stream is null");
		String fileName = null;
		//如果未指定文件名，则取responseHeader里面的文件名
		if(specFileName == null){
			String contentDispostion = conn.getHeaderField("Content-Disposition");
			if(!TextUtils.isEmpty(contentDispostion) && contentDispostion.indexOf("filename=")!=-1){
				contentDispostion = URLDecoder.decode(contentDispostion, "UTF-8");
				fileName = contentDispostion.substring(contentDispostion.indexOf("filename=") + 9);
			}
		}else{
			fileName = specFileName;
		}
		
		if(fileName == null){
			throw new DownloadException("文件信息不完整");
		}
		String fileFullPath = savePath + (savePath.endsWith("/")? "" : "/") + fileName;
		FileOutputStream fos = new FileOutputStream(fileFullPath);
		// 把数据存入路径+文件名
		byte buf[] = new byte[1024];
		listener.sendProgress("fileSize", fileSize,false);
		do {
			// 循环读取
			int numread = is.read(buf);
			if (numread == -1) {
				break;
			}
			fos.write(buf, 0, numread);
			downLoadFileSize += numread;

			// 更新进度条
			if (downLoadFileSize==fileSize){
				Log.e("TAG", "downloadFile: "+downLoadFileSize);
				listener.sendProgress("progress", downLoadFileSize,true);
			}else {
				listener.sendProgress("progress", downLoadFileSize,false);
			}

		} while (!cancelLock.isCancelFlag());
		try {
			is.close();
			fos.close();
		} catch (Exception ex) {
		}
		return cancelLock.isCancelFlag() ? null : fileFullPath;
	}
	
	public boolean isCanceled(){
		return this.cancelLock.isCancelFlag();
	}
	
	public static class CancelLock{
		private boolean cancelFlag;

		public boolean isCancelFlag() {
			return cancelFlag;
		}

		public void setCancelFlag(boolean cancelFlag) {
			this.cancelFlag = cancelFlag;
		}
		
	}
	
	public interface DownloadListener{
		
		void sendProgress(Object... objects);
	}
	
	public static class DownloadException extends Exception {
		private static final long serialVersionUID = -8434344288763060179L;
		
		public DownloadException(String msg){
			super(msg);
		}
	}
	public static void pageJsonDownLoad(final String uid, String sdcardRoot, final String projectId) {
		String readFile = FileUtil.readFile(sdcardRoot);//读取本地json文件
		Log.e("READFILE", "pageJsonDownLoad: "+readFile);
		try {
			JSONObject jsonObject = new JSONObject(readFile);
			JSONObject jsonObject2 = jsonObject.getJSONObject("project");
			final String lastModifyTime1 = jsonObject2.getString("lastModifyTime");
			JSONArray publish = jsonObject2.getJSONArray("publish");
			for (int i = 0; i < publish.length(); i++) {
				JSONObject jsonObject3 = publish.getJSONObject(i);
				int index = jsonObject3.getInt("index");
				JSONArray pages = jsonObject3.getJSONArray("pages");
				for (int j = 0; j < pages.length(); j++) {
					JSONObject jsonObject4 = pages.getJSONObject(j);
					 final String pageId = jsonObject4.getString("id");

					Log.e("PAGEID", "pageJsonDownLoad: "+pageId);
					HttpUtil.getPageOkHttpClient(new Callback() {
						@Override
						public void onFailure(Call call, IOException e) {
						}
						@Override
						public void onResponse(Call call, Response response) throws IOException {

							String resp = response.body().string();
							Log.e("PAGE", "onResponse: ----" + resp+"===="+projectId+"----"+lastModifyTime1);
							try {
								JSONObject jsonObject = new JSONObject(resp);
								JSONObject jsonObject1 = jsonObject.getJSONObject("data");
								String jsonStr = jsonObject1.toString();

								//存储方案的json文件,成功
								String jsonPath = ResourceFileManager.createOrGetUserProfileDir(uid) + File.separator + projectId;

								File file = new File(jsonPath);
								if (!file.exists()) {
									boolean mkdirs = file.mkdirs();
									Log.e("mkdirs", "onResponse: "+mkdirs );
								}
								String path = jsonPath + "/" + pageId + ".json";
								Log.e("JSONPATH", "onResponse: "+path);
								File filePath = new File(path);
								if (!filePath.exists()) {
									boolean newFile = filePath.createNewFile();
									Log.e("CREATE", "onResponse: "+newFile);
								}
								FileOutputStream fos = new FileOutputStream(filePath);
								fos.write(jsonStr.getBytes());
								Log.e("OUTPUT", "onResponse:写入文件成功！！ ");
								fos.close();
							} catch (JSONException e) {
								e.printStackTrace();
							}
						}
					}, pageId, lastModifyTime1);

				}
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}
}
